<?php

/**
	Bandit Sliders Module

	The contents of this file are subject to the terms of the GNU General
	Public License Version 2.0. You may not use this file except in
	compliance with the license. Any of the license terms and conditions
	can be waived if you get permission from the copyright holder.

	Copyright (c) 2011 Bandit Media
	Jermaine Marée

	Inspired by Sawyer Hollenshead's Social Bartender
	http://shakenandstirredweb.com/plugins/social-bartender/

		@package BanditSliders
		@version 1.1
**/

//! Bandit Social
class BanditSliders extends FeatherBase {

	protected static
		//! Module Hook
		$hook,
		// Option
		$option,
		//! URL
		$url,
		//! Path
		$path;

	/**
		Initialize module
			@public
	**/
	static function init() {
		// Get Option
		self::$option = get_option('bandit_slider');
		// Set default option
		if(self::$option == FALSE) { update_option('bandit_slider',''); }
		// Set Path
		self::$path = FEATHER_THEME_PATH.'modules/bandit-sliders/';
		// Set URL
		self::$url = FEATHER_THEME_URL.'modules/bandit-sliders/';
		// Admin init
		add_action('admin_init',__CLASS__.'::admin_init');
	}

	/**
		Admin init
			@public
	**/
	static function admin_init() {
		// Set Hook
		self::$hook = get_plugin_page_hook('banditmod','themes.php');
		// Get Tab
		$current_tab = FeatherAdmin::get_current_tab(BanditAdmin::$module_tabs);
		// Register settings
		register_setting('bandit-slider-settings','bandit_slider',
			__CLASS__.'::validate_settings');
		// Is module current tab?
		if('sliders'==$current_tab) {
			// Module styles
			add_action('admin_print_styles-'.self::$hook,__CLASS__.'::styles');
			// Module scripts
			add_action('admin_print_scripts-'.self::$hook,__CLASS__.'::scripts');
		}
	}

	/**
		Admin stylesheets
			@public
	**/
	static function styles() {
		// Register style
		if(version_compare('3.3',get_bloginfo('version'),'>')):
			wp_register_style('bandit-slider-css',self::$url.'bandit-slider.css',array('thickbox','nav-menu'));
		else:
			wp_register_style('bandit-slider-css',self::$url.'bandit-slider.css', array('wp-admin','thickbox'));
		endif;
		// Enqueue style
		wp_enqueue_style('bandit-slider-css');
	}

	/**
		Admin javascript
			@public
	**/
	static function scripts() {
		// Register script
		wp_register_script('bandit-slider-js',self::$url.'bandit-slider.js', 
			array('jquery','media-upload','thickbox','jquery-ui-core','jquery-ui-sortable'));
		// Enqueue script
		wp_enqueue_script('bandit-slider-js');
	}

	/**
		Validate settings
			@public
	**/
	static function validate_settings($input) {
		// Get action
		$action = esc_attr($input['action']);

		// New slider
		if($action == 'new') {
			// Get current options
			$valid=get_option('bandit_slider');
			// Any options exist?
			if(!$valid) { $valid = array(); }
			// Limit number of slider items
			if(count($valid) > 4) {
				// Settings saved notice
				add_settings_error('feather_setting_notices',
					esc_attr('settings_updated'),__('You cannot create more than 5 sliders.'),'error');
				// Return
				return $valid;
			}
			// Validate input
			$name = esc_attr($input['name']);
			$type = 'image';
			// Generate slug
			$slug = sanitize_title_with_dashes($name);
			// Check slug
			if(isset($valid[$slug])) {
				for($i=1;$i<9;$i++) {
					if(!isset($valid[$slug.$i])) {
						$slug = $slug.$i;
						break;
					}
				}
			}
			// Add slider
			$valid[$slug] = array('name'=>$name,'type'=>'image');
			// Modify referer
			$_REQUEST['_wp_http_referer']=admin_url('themes.php?page=banditmod&tab=sliders&slider='.$slug);
			// Settings saved notice
			add_settings_error('feather_setting_notices',
				esc_attr('settings_updated'),__('Slider created.'),'updated');
			// Return validated settings
			return $valid;
		}

		// Add image item to slider
		if($action == 'add_image') {
			// Get current options
			$valid=get_option('bandit_slider');
			// Slider
			$slider = esc_attr($input['slider']);
			// Can item be added?
			if(isset($valid[$slider])) {
				// Item array exist?
				if(!isset($valid[$slider]['items'])) { $valid[$slider]['items'] = array(); }
				// Validate input
				$caption = isset($input['caption'])?wp_kses_data($input['caption']):'';
				$link = isset($input['link'])?esc_url($input['link']):'';
				$image = isset($input['image'])?esc_url($input['image']):'';
				$image_id = self::get_image_id($image);
				$image_alt = $input['image_alt']?esc_attr($input['image_alt']):basename($image);
				// Check if image stored in db
				if($image_id):
					// Add to slider
					$valid[$slider]['items'][] = array(
						'caption' => $caption,
						'link' => $link,
						'image' => $image,
						'image_id' => $image_id,
						'image_alt' => $image_alt
					);
					add_settings_error('feather_setting_notices',
						esc_attr('settings_updated'),__('Image added.'),'updated');
				else:
					// Settings saved notice
					add_settings_error('feather_setting_notices',
						esc_attr('settings_updated'),__('Image not added. Make sure you add the full-sized image.'),'error');
				endif;
			}
			return $valid;
		}

		// Update slider
		if($action == 'update') {
			// Get current options
			$valid=get_option('bandit_slider');
			// Get  slider
			$slider = esc_attr($input['slider']);
			// Create tmp array
			$tmp = array();
			// Validate name
			$tmp['name'] = esc_attr($input['name']);
			$tmp['type'] = 'image';
			// Items exist?
			if(isset($input['items'])) {
				// Items array
				$tmp['items'] = array();
				// Validate items
				foreach($input['items'] as $item) {
					// Validate item input
					$caption = wp_kses_data($item['caption']);
					$link = esc_url($item['link']);
					$image = esc_url($item['image']);
					$image_id = self::get_image_id($image);
					$image_alt = $item['image_alt']?esc_attr($item['image_alt']):basename($image);
					// Add item to slider
					$tmp['items'][] = array(
						'caption' => $caption,
						'link' => $link,
						'image' => $image,
						'image_id' => $image_id,
						'image_alt' => $image_alt
					);
				}	
			}
			// Update menu
			$valid[$slider] = $tmp;
			// Settings saved notice
			add_settings_error('feather_setting_notices',
				esc_attr('settings_updated'),__('Slider updated.'),'updated');
			// Return validated settings
			return $valid;
		}

		// Delete slider
		if($action == 'delete') {
			// Modify referer
			$_REQUEST['_wp_http_referer']=admin_url('themes.php?page=banditmod&tab=sliders');
			// Get current options
			$valid=get_option('bandit_slider');
			// Delete slider
			if(isset($input['slider'])) {
				$slider = esc_attr($input['slider']);
				unset($valid[$slider]);
			}
			// Settings saved notice
			add_settings_error('feather_setting_notices',
				esc_attr('settings_updated'),__('Slider deleted.'),'updated');
			// Return validated settings
			return $valid;
		}
	}

	/**
		Nav Tabs
			@public
	**/
	static function nav_tabs() {
		if(self::$option && is_array(self::$option)) {
			$output = '';
			// Get current slider
			$current = self::get_current_slider();				
			// Loop through sliders
			foreach(self::$option as $key=>$attrs) {
				if($key == $current):
					$output .= '<span class="nav-tab nav-tab-active">'.$attrs['name'].'</span>';
				else:
					$url = admin_url('themes.php?page=banditmod&tab=sliders&slider='.$key);
					$output .= '<span class="nav-tab"><a href="'.$url.'">'.$attrs['name'].'</a></span>';
				endif;
			}
		} else {
			$output = '<span class="nav-tab">No Sliders Created</span>';
		}
		// Print tabs
		echo $output;
	}

	/**
		Get current slider
			@public
	**/
	static function get_current_slider() {
		if(self::$option && is_array(self::$option)) {
			$slider = isset($_GET['slider'])?esc_attr($_GET['slider']):key(self::$option);
		} else {
			$slider = FALSE;
		}
		return $slider;
	}

	/**
		Get sliders
			@public
	**/
	static function get_sliders() {
		$sliders=get_option('bandit_slider');
		if($sliders && is_array($sliders)) {
			$result = array('disabled'=>'Disabled');
			foreach($sliders as $key=>$attrs) {
				if(isset($sliders[$key]['items']))
					$result[$key]=$attrs['name'];
			}
		} else {
			$result = array('0'=>'No Sliders Available');
		}
		return $result;
	}

	/**
		Get slider
			@public
	**/
	static function get_slider($slider=NULL) {
		return isset(self::$option[$slider])?self::$option[$slider]:FALSE;
	}

	/**
		Get image ID
			@public
	**/
	static function get_image_id($url) {
		global $wpdb;
		$id = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT ID FROM $wpdb->posts WHERE guid = '$url'"
				)
			);
		return $id;
	}

}